# LoginPage.py
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException

class LoginPage:
    def __init__(self, driver):
        self.driver = driver
        self.url = 'https://www.macrozheng.com/admin'
        self.success_message = (By.XPATH, "//span[@class='no-redirect' and contains(text(), '仪表盘')]")
        self.username_input = (By.XPATH, "//input[@name='username']")
        self.password_input = (By.XPATH, "//input[@name='password']")
        self.login_button = (By.XPATH, "//button[@class='el-button el-button--primary']/span[contains(text(), '登录')]")

    def navigate(self):
        # 导航到登录页面
        self.driver.get(self.url)

    def wait_for_element_visible(self, locator, timeout=10):
        # 显示等待直到元素可见
        element = WebDriverWait(self.driver, timeout).until(
            EC.visibility_of_element_located(locator)
        )
        return element

    def clear_username_input(self):
        # 清除用户名输入框的内容
        username_input = self.wait_for_element_visible(self.username_input)
        # username_input.clear()
        username_input.send_keys(Keys.CONTROL + "a") 
        username_input.send_keys(Keys.DELETE)  

    def clear_password_input(self):
        # 清除密码输入框的内容
        password_input = self.wait_for_element_visible(self.password_input)
        # password_input.clear()
        password_input.send_keys(Keys.CONTROL + "a") 
        password_input.send_keys(Keys.DELETE)  

    def enter_username(self, username):
        # 输入用户名
        username_input = self.wait_for_element_visible(self.username_input)
        username_input.send_keys(username)

    def enter_password(self, password):
        # 输入密码
        password_input = self.wait_for_element_visible(self.password_input)
        password_input.send_keys(password)

    def click_login_button(self):
        # 点击登录按钮
        login_button = self.wait_for_element_visible(self.login_button)
        login_button.click()

    def is_user_logged_in(self):
        # 检查用户是否已登录
        # return 'https://www.macrozheng.com/admin/#/home' in self.driver.current_url
        try:
            element = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located(self.success_message)
            )
            if element.is_displayed():
                return True
            else:
                return False
        except TimeoutException:
            print("元素规定时间内不存在")
            return False
            
    def get_error_message(self):
        # 获取错误消息
        error_message_element = self.wait_for_element_visible(self.error_message_locator)
        return error_message_element.text